<template>
  <div class="home-container">
    <!-- 顶部统计卡片区域 -->
    <div class="stat-cards">
      <el-card class="statistic-card" v-for="(card, index) in statCards" :key="index">
        <div class="card-content">
          <div class="card-icon" :style="{ backgroundColor: card.color }">
            <el-icon :size="32">
              <component :is="card.icon" />
            </el-icon>
          </div>
          <div class="card-info">
            <div class="card-title">{{ card.title }}</div>
            <div class="card-value" :style="{ color: card.color }">{{ card.format(animatedValues[index]) }}</div>
            <div class="card-subtitle">
              <span>较上周</span>
              <span :class="['trend', card.trend === 'up' ? 'trend-up' : 'trend-down']">
                <el-icon>
                  <component :is="card.trend === 'up' ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                {{ card.trendValue }}
              </span>
            </div>
          </div>
        </div>
      </el-card>
      
      <el-card class="statistic-card message-card" @click="handleMessageCardClick">
        <div class="card-content">
          <div class="card-icon" style="background-color: #F56C6C">
            <el-icon :size="32"><Bell /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-title">系统消息</div>
            <div class="card-value" style="color: #F56C6C">{{ unreadMessageCount }}</div>
            <div class="card-subtitle">
              <span>未读消息</span>
              <span :class="['trend', unreadTrend === 'up' ? 'trend-up' : 'trend-down']">
                <el-icon v-if="unreadTrend === 'up'"><ArrowUp /></el-icon>
                <el-icon v-else><ArrowDown /></el-icon>
                {{ unreadTrendValue }}
              </span>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 内容区域 -->
    <div class="content-section">
      <!-- 左侧图表区域 -->
      <div class="chart-section">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>访问统计</span>
              <div class="chart-tabs">
                <el-radio-group v-model="visitPeriod" size="small" @change="handlePeriodChange">
                  <el-radio-button value="week" label="本周"></el-radio-button>
                  <el-radio-button value="month" label="本月"></el-radio-button>
                  <el-radio-button value="year" label="全年"></el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-container-wrapper">
            <div id="visitChart" class="chart-container"></div>
          </div>
        </el-card>
        
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>用户分布</span>
            </div>
          </template>
          <div class="chart-container-wrapper">
            <div id="userDistributionChart" class="chart-container"></div>
          </div>
        </el-card>
      </div>
      
      <!-- 右侧消息面板 -->
      <div class="message-section">
        <div class="messages-container">
          <el-card class="message-panel">
            <template #header>
              <div class="message-panel-header">
                <span>系统消息</span>
                <span class="read-all" @click="handleMessageRead(0)">全部已读</span>
              </div>
            </template>
            <el-tabs v-model="activeTab">
              <el-tab-pane label="全部" name="all">
                <div class="message-list">
                  <div class="message-item system">
                    <el-icon class="message-icon"><Setting /></el-icon>
                    <div class="message-content">
                      <div class="message-title">系统升级通知</div>
                      <div class="message-text">系统将于今晚24:00进行升级维护，预计持续2小时，请提前做好准备。</div>
                      <div class="message-time">4天前</div>
                    </div>
                  </div>
                  
                  <div class="message-item">
                    <el-icon class="message-icon"><UserFilled /></el-icon>
                    <div class="message-content">
                      <div class="message-title">新用户注册提醒</div>
                      <div class="message-text">今日新增注册用户10名，请及时查看并审核。</div>
                      <div class="message-time">5天前</div>
                    </div>
                  </div>
                  
                  <div class="message-item">
                    <el-icon class="message-icon"><Document /></el-icon>
                    <div class="message-content">
                      <div class="message-title">待审核内容提醒</div>
                      <div class="message-text">有5篇新文章等待审核，请尽快处理。</div>
                      <div class="message-time">5天前</div>
                    </div>
                  </div>
                  
                  <div class="message-item warning">
                    <el-icon class="message-icon"><Warning /></el-icon>
                    <div class="message-content">
                      <div class="message-title">安全警告</div>
                      <div class="message-text">检测到异常登录行为，IP地址: 192.168.1.1，请确认是否为您本人操作。</div>
                      <div class="message-time">5天前</div>
                    </div>
                  </div>
                  
                  <div class="message-item">
                    <el-icon class="message-icon"><Service /></el-icon>
                    <div class="message-content">
                      <div class="message-title">服务器状态预警</div>
                      <div class="message-text">服务器CPU使用率超过90%，请检查系统运行状态。</div>
                      <div class="message-time">5天前</div>
                    </div>
                  </div>
                  
                  <div class="message-item">
                    <el-icon class="message-icon"><Bell /></el-icon>
                    <div class="message-content">
                      <div class="message-title">其他通知</div>
                      <div class="message-text">这是一条测试消息，请忽略。</div>
                      <div class="message-time">6天前</div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="未读" name="unread">
                <div class="message-list">
                  <!-- 未读消息 -->
                </div>
              </el-tab-pane>
              <el-tab-pane label="系统通知" name="system">
                <div class="message-list">
                  <!-- 系统通知 -->
                </div>
              </el-tab-pane>
              <el-tab-pane label="任务提醒" name="task">
                <div class="message-list">
                  <!-- 任务提醒 -->
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, defineComponent, nextTick } from 'vue'
import * as echarts from 'echarts'
import { useChart } from '../utils/chartUtils'
import { ArrowUp, ArrowDown, User, View, Document, Bell, Setting, UserFilled, Warning, Service } from '@element-plus/icons-vue'

// 统计卡片数据
const statCards = [
  {
    title: '用户总数',
    value: '1,234',
    numericValue: 1234,
    format: (val: number) => val.toLocaleString(),
    color: '#409EFF',
    icon: 'User',
    trend: 'up',
    trendValue: '12%'
  },
  {
    title: '访问量',
    value: '45,678',
    numericValue: 45678,
    format: (val: number) => val.toLocaleString(),
    color: '#67C23A',
    icon: 'View',
    trend: 'up',
    trendValue: '25.8%'
  },
  {
    title: '文章数',
    value: '356',
    numericValue: 356,
    format: (val: number) => val.toLocaleString(),
    color: '#E6A23C',
    icon: 'Document',
    trend: 'up',
    trendValue: '5.2%'
  }
]

// 动画显示的值
const animatedValues = ref(statCards.map(() => 0))

// 未读消息数据
const unreadMessageCount = ref(6)
const unreadTrend = ref('down')
const unreadTrendValue = ref('8.1%')

// 动画效果函数
const animateValues = () => {
  // 为每个卡片创建动画
  statCards.forEach((card, index) => {
    const targetValue = card.numericValue
    const duration = 2000 // 动画持续2秒
    const startTime = Date.now()
    
    const animate = () => {
      const currentTime = Date.now()
      const elapsed = currentTime - startTime
      
      if (elapsed < duration) {
        // 使用easeOutExpo缓动函数让动画更自然
        const progress = 1 - Math.pow(1 - elapsed / duration, 3)
        animatedValues.value[index] = Math.floor(targetValue * progress)
        requestAnimationFrame(animate)
      } else {
        animatedValues.value[index] = targetValue
      }
    }
    
    animate()
  })
  
  // 为未读消息数量创建动画
  const targetValue = unreadMessageCount.value
  const duration = 2000 // 动画持续2秒
  const startTime = Date.now()
  
  const animateUnread = () => {
    const currentTime = Date.now()
    const elapsed = currentTime - startTime
    
    if (elapsed < duration) {
      // 使用easeOutExpo缓动函数让动画更自然
      const progress = 1 - Math.pow(1 - elapsed / duration, 3)
      unreadMessageCount.value = Math.floor(targetValue * progress)
      requestAnimationFrame(animateUnread)
    } else {
      unreadMessageCount.value = targetValue
    }
  }
  
  animateUnread()
}

// 访问统计时间段
const visitPeriod = ref('week')

// 消息面板引用
const messagePanelRef = ref()

const activeTab = ref('all')

// 使用图表钩子
const { 
  initChart: initVisitChart, 
  updateChart: updateVisitChart, 
  disposeChart: disposeVisitChart 
} = useChart('visitChart', 'visitChart')

const { 
  initChart: initDistributionChart, 
  updateChart: updateDistributionChart, 
  disposeChart: disposeDistributionChart 
} = useChart('userDistributionChart', 'userDistributionChart')

// 访问数据
const weekData = [120, 200, 150, 80, 70, 110, 130]
const monthData = [320, 302, 341, 374, 390, 450, 420, 432, 421, 410, 394, 390, 
                 432, 421, 410, 394, 390, 320, 302, 341, 374, 390, 450, 420,
                 410, 394, 390, 432, 421, 410]
const yearData = [900, 850, 950, 1000, 1100, 1050, 1000, 1200, 1100, 1050, 900, 850]

// 处理消息卡片点击
const handleMessageCardClick = () => {
  // 滚动到消息面板区域
  const messageSection = document.querySelector('.message-section')
  if (messageSection) {
    messageSection.scrollIntoView({ behavior: 'smooth' })
  }
}

// 处理消息已读
const handleMessageRead = (count: number) => {
  unreadMessageCount.value = count
}

// 获取访问统计图表配置
const getVisitChartOption = () => {
  let xAxisData: string[] = []
  let seriesData: number[] = []
  
  if (visitPeriod.value === 'week') {
    xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    seriesData = weekData
  } else if (visitPeriod.value === 'month') {
    xAxisData = Array.from({ length: 30 }, (_, i) => `${i + 1}日`)
    seriesData = monthData
  } else if (visitPeriod.value === 'year') {
    xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    seriesData = yearData
  }
  
  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: xAxisData,
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '访问量',
        type: 'bar',
        barWidth: '60%',
        data: seriesData,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  }
  
  return option
}

// 获取用户分布图表配置
const getUserDistributionOption = () => {
  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '用户分布',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 1048, name: '普通用户' },
          { value: 735, name: '管理员' },
          { value: 580, name: '编辑' },
          { value: 484, name: '访客' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  return option
}

// 时间段切换处理
const handlePeriodChange = () => {
  updateVisitChart(getVisitChartOption())
}

// 组件挂载后初始化图表
onMounted(() => {
  // 启动数值动画
  animateValues();
  
  // 等待DOM完全渲染
  nextTick(() => {
    initCharts();
  });
});

// 初始化所有图表
const initCharts = async () => {
  // 确保DOM已经渲染并且有尺寸
  setTimeout(async () => {
    try {
      // 初始化访问统计图表
      initVisitStatChart();
      
      // 初始化用户分布图表
      initUserDistributionChart();
      
    } catch (error) {
      console.error('图表初始化错误:', error);
    }
    
    // 获取MessagePanel组件的未读消息数
    if (messagePanelRef.value) {
      unreadMessageCount.value = messagePanelRef.value.unreadCount || 6;
    }
  }, 300);
};

// 初始化访问统计图表
const initVisitStatChart = async () => {
  // console.log('开始初始化访问统计图表...');
  let retries = 0;
  const maxRetries = 3;
  
  const tryInitVisitChart = async () => {
    try {
      const visitChartEl = document.getElementById('visitChart');
      if (!visitChartEl) {
        throw new Error('访问统计图表DOM元素不存在');
      }
      
      // console.log('访问统计图表DOM尺寸:', visitChartEl.clientWidth, visitChartEl.clientHeight);
      
      if (visitChartEl.clientWidth <= 0 || visitChartEl.clientHeight <= 0) {
        throw new Error('访问统计图表DOM元素尺寸为0');
      }
      
      const chart = await initVisitChart();
      if (chart) {
        // console.log('访问统计图表初始化成功');
        updateVisitChart(getVisitChartOption());
      } else {
        throw new Error('访问统计图表初始化返回null');
      }
    } catch (error) {
      console.error(`访问统计图表初始化失败(${retries + 1}/${maxRetries}):`, error);
      
      if (retries < maxRetries) {
        retries++;
        console.log(`重试访问统计图表初始化... ${retries}/${maxRetries}`);
        setTimeout(() => {
          tryInitVisitChart();
        }, 300 * retries);
      }
    }
  };
  
  tryInitVisitChart();
};

// 初始化用户分布图表
const initUserDistributionChart = async () => {
  // console.log('开始初始化用户分布图表...');
  let retries = 0;
  const maxRetries = 3;
  
  const tryInitDistributionChart = async () => {
    try {
      const distChartEl = document.getElementById('userDistributionChart');
      if (!distChartEl) {
        throw new Error('用户分布图表DOM元素不存在');
      }
      
      // console.log('用户分布图表DOM尺寸:', distChartEl.clientWidth, distChartEl.clientHeight);
      
      if (distChartEl.clientWidth <= 0 || distChartEl.clientHeight <= 0) {
        throw new Error('用户分布图表DOM元素尺寸为0');
      }
      
      const chart = await initDistributionChart();
      if (chart) {
        // console.log('用户分布图表初始化成功');
        updateDistributionChart(getUserDistributionOption());
      } else {
        throw new Error('用户分布图表初始化返回null');
      }
    } catch (error) {
      console.error(`用户分布图表初始化失败(${retries + 1}/${maxRetries}):`, error);
      
      if (retries < maxRetries) {
        retries++;
        // console.log(`重试用户分布图表初始化... ${retries}/${maxRetries}`);
        setTimeout(() => {
          tryInitDistributionChart();
        }, 300 * retries);
      }
    }
  };
  
  tryInitDistributionChart();
};

// 组件卸载前销毁图表实例
onBeforeUnmount(() => {
  disposeVisitChart()
  disposeDistributionChart()
})
</script>

<style scoped>
.home-container {
  padding: var(--content-padding);
  width: 100%;
  box-sizing: border-box;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.content-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-section {
  flex: 2;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message-section {
  flex: 1;
  height: 720px;
  margin-bottom: 20px;
}

.messages-container {
  height: 100%;
}

.message-panel {
  height: 100%;
}

.message-panel :deep(.el-card__body) {
  height: calc(100% - 60px);
  padding: 0;
}

.message-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.read-all {
  font-size: 12px;
  color: var(--el-color-primary);
  cursor: pointer;
}

.message-panel :deep(.el-tabs) {
  height: 100%;
}

.message-panel :deep(.el-tabs__content) {
  height: calc(100% - 40px);
  overflow: auto;
}

.message-list {
  padding: 0 15px;
}

.message-item {
  padding: 15px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
  display: flex;
  align-items: flex-start;
}

.message-icon {
  font-size: 20px;
  margin-right: 12px;
  margin-top: 2px;
  color: var(--el-color-info);
}

.system .message-icon {
  color: var(--el-color-primary);
}

.warning .message-icon {
  color: var(--el-color-danger);
}

.message-content {
  flex: 1;
}

.message-title {
  font-weight: 500;
  margin-bottom: 5px;
}

.message-text {
  font-size: 13px;
  color: var(--el-text-color-secondary);
  margin-bottom: 5px;
  line-height: 1.5;
}

.message-time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.chart-card {
  margin-bottom: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}

.chart-card :deep(.el-card__body) {
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  padding: 12px 20px;
}

.chart-container-wrapper {
  position: relative;
  height: 350px;
  width: 100%;
  flex: 1;
  min-height: 0;
}

.chart-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

/* 统计卡片样式 */
.statistic-card {
  transition: all 0.3s;
  cursor: pointer;
}

.statistic-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  align-items: center;
}

.card-icon {
  width: 64px;
  height: 64px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 16px;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: var(--text-secondary, #909399);
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  margin: 8px 0;
  transition: color 0.3s ease;
}

.card-subtitle {
  font-size: 12px;
  color: var(--text-secondary, #909399);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.trend {
  display: flex;
  align-items: center;
  font-weight: 500;
}

.trend-up {
  color: #67C23A;
}

.trend-down {
  color: #F56C6C;
}

.trend .el-icon {
  margin-right: 4px;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .stat-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .chart-container-wrapper {
    height: 300px;
  }
}

@media (max-width: 960px) {
  .content-section {
    flex-direction: column;
  }
  
  .message-section {
    height: 600px;
  }
}

@media (max-width: 768px) {
  .home-container {
    padding: 10px;
  }
  
  .stat-cards {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }
  
  .content-section {
    gap: 15px;
  }
  
  .chart-section {
    gap: 15px;
  }
  
  .chart-container-wrapper {
    height: 250px;
  }
  
  .message-section {
    height: 500px;
  }
  
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
  }
}

@media (max-width: 480px) {
  .home-container {
    padding: 8px;
  }
  
  .stat-cards {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .content-section {
    gap: 10px;
  }
  
  .chart-section {
    gap: 10px;
  }
  
  .chart-container-wrapper {
    height: 200px;
  }
  
  .message-section {
    height: 400px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .chart-card {
    background-color: var(--el-bg-color-overlay, #1d1e1f);
    color: var(--el-text-color-primary, #e5eaf3);
  }
}

/* 适配触摸设备 */
@media (hover: none) {
  .chart-tabs .el-radio-button {
    padding: 8px 12px;
  }
}

/* 打印样式优化 */
@media print {
  .home-container {
    padding: 0;
  }
  
  .chart-container-wrapper {
    page-break-inside: avoid;
  }
}
</style> 